import type { AxiosInstance } from 'axios';
import axios from 'axios';

import localINFO from '../localInfo';

const ip = import.meta.env.VITE_IP || window.location.hostname;
const port = import.meta.env.VITE_PORT || '30001';

let baseURL = `http://${ip}:${port}`;

if (import.meta.env.VITE_BUILD_MODE === 'proxy') {
  const { protocol, hostname, port } = window.location;
  baseURL = `${protocol}//${hostname}:${port}/v1`;
}

export const getHeaders = () => {
  const token = localINFO.getToken();
  return { Authorization: token ? `Bearer ${token}` : '' };
};

// 创建 Axios 实例的函数
function createAxiosInstance(baseURL: string, options = {}): AxiosInstance {
  const instance = axios.create({
    baseURL,
    headers: {
      'Content-Type': 'application/json',
    },
    ...options,
  });

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      const token = localINFO.getToken();

      const access_token = token ? token : null;
      if (access_token) {
        config.headers['Authorization'] = `Bearer ${access_token}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    },
  );

  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      if (
        response.config.url === '/file/downloadFile' ||
        response.config.url === '/file/downloadFiles'
      ) {
        return response;
      }

      if (response.status === 200) {
        return response.data;
      }

      return response;
    },
    (error) => {
      const response = error.response;
      if (response && response.status === 401) {
        localINFO.clear();
        window.location.href = '/login';
        alert('登录过期或失效，请重新登录');
      }
      return Promise.reject(error);
    },
  );

  return instance;
}

// 创建默认的 Axios 实例
const ReqInstance: AxiosInstance = createAxiosInstance(baseURL);

export function fetchPost(url: string, params: any, isFormData = false) {
  const headers = isFormData
    ? {
        'Content-Type': 'multipart/form-data',
        Accept: 'application/json',
      }
    : {
        'Content-Type': 'application/json',
      };
  return ReqInstance.post(url, params, { headers });
}

export function fetchBodyPost(url: string, params: any, isFormData = false) {
  const headers = isFormData
    ? {
        'Content-Type': 'multipart/form-data',
        Accept: 'application/json',
      }
    : {
        'Content-Type': 'application/json',
      };

  return ReqInstance.post(url, params, {
    headers,
    responseType: 'blob',
  });
}

export function fetchGet(url: string, params: any) {
  return ReqInstance.get(url, { params });
}

export function fetchBodyGet(url: string, params: any) {
  return ReqInstance.get(url, { params, responseType: 'blob' });
}
